/*
 * @Author: wwssaabb
 * @Date: 2021-09-08 09:56:17
 * @LastEditTime: 2021-09-08 11:31:39
 * @FilePath: \gshop-client\src\api\http.ts
 */
import axios, { Method, AxiosResponse, AxiosError } from "axios";
import { Toast } from "vant";

const BASE_URL = "http://localhost:8080/";
const acceptMethods = ["GET", "POST", "PUT", "DELETE", "PATCH"];

type InstanceMethods = "get" | "delete" | "post" | "put" | "patch";

//创建axios实例对象
const instance = axios.create({
  baseURL: BASE_URL, //统一域名
  timeout: 6000, //设置超时
});

//==============请求拦截器==============
instance.interceptors.request.use(
  (config) => {
    return config;
  },
  (err) => {
    //请求错误时do something...
    Toast.fail("请求错误" + err);
    return Promise.reject(err);
  }
);

//==============响应拦截器==============
instance.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (err) => Promise.reject(err)
);

//==============导出封装函数==============
export default function (
  method: InstanceMethods = "get",
  url: string,
  data: object | null = null
  // headers: object | null = null
) {
  return new Promise((resolve) => {
    if (!acceptMethods.includes(method)) {
      Toast.fail("不支持" + method + "请求方法");
      // return Promise.reject("不支持" + method + "请求方法");
    }
    let promise;
    if (method === "get") {
      promise = instance.get(url, { data });
    } else {
      promise = instance[method](url, data);
    }

    promise
      .then((res: AxiosResponse) => resolve(res.data))
      .catch((error: AxiosError) => Toast.fail(error));
  });
}
